package com.ddddddl.zhangben;

import java.util.Calendar;

import com.ddddddl.zhangben.data.Account;
import com.ddddddl.zhangben.data.Type;
import com.ddddddl.zhangben.logic.AccountLogic;
import com.ddddddl.zhangben.logic.Request;
import com.ddddddl.zhangben.logic.RequestListener;

import static com.ddddddl.zhangben.logic.AccountLogic.*;

import com.ddddddl.zhangben.ui.adapter.TypeAdapter;
import com.ddddddl.zhangben.ui.widget.AmountKeybroadView;
import com.ddddddl.zhangben.util.CalendarUtils;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class EditActivity extends BaseActivity implements OnClickListener, OnItemClickListener, RequestListener{
	
	private ListView mFirstTypeList;
	private ListView mSecondTypeList;
	private Button mAccountDate;
	private EditText mAmount;
	private TypeAdapter mSecondTypeAdapter;
	private TypeAdapter mFirstTypeAdapter;
	protected int mMonth;
	protected int mYear;
	protected int mDay;
	private PopupWindow mPopupWindow;
	
	private static final int DATE_DIALOG_ID = 0;
	private static final int DIALOG_UPDATE_FIRST_TYPE = 1;
	private static final int DIALOG_UPDATE_SECOND_TYPE = 2;
	private static final int DIALOG_ADD_TYPE = 3;
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

				public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
	private AmountKeybroadView mAmountKeybroadView;
	private Button mSaveAccount;
	private Account mAccountForEdit;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);
        
        mFirstTypeList = (ListView) findViewById(R.id.first_level_type_list);
        mFirstTypeAdapter = new TypeAdapter(this);
		mFirstTypeList.setAdapter(mFirstTypeAdapter);
		mFirstTypeList.setOnItemClickListener(this);
		
        mSecondTypeList = (ListView) findViewById(R.id.second_level_type_list);
        mSecondTypeAdapter = new TypeAdapter(this);
        mSecondTypeList.setAdapter(mSecondTypeAdapter);
        mSecondTypeList.setOnItemClickListener(this);
        
        mAccountDate = (Button) findViewById(R.id.account_date);
        mAccountDate.setOnClickListener(this);
        
        mAmount = (EditText) findViewById(R.id.account_amount);
        mAmount.setFilters(new InputFilter[] {new InputFilter() {
			
			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {
				String dValue = dest.toString();
		        String[] splitArray = dValue.split("\\.");
		        if (splitArray.length > 1) {
		            String dotValue = splitArray[1];
		            int diff = dotValue.length();
		            if (diff > 0) {
		                return "";
		            }
		        }
				return null;
			}
		}});
        
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        updateDisplay();
        
        AccountLogic.getInstance().sendRequest(new Request(REQ_TYPE_INIT, this));
        
        mAmountKeybroadView = new AmountKeybroadView(this);
        mSaveAccount = (Button) mAmountKeybroadView.findViewById(R.id.save_account);
        mSaveAccount.setOnClickListener(this);
        mPopupWindow = new PopupWindow(mAmountKeybroadView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);  
        mAmountKeybroadView.setEdittext(mAmount);
        
        mAccountForEdit = getIntent().getParcelableExtra(AccountListActivity.PARAM_ACCOUNT);
        if (mAccountForEdit != null) {
			mAmount.setText(String.valueOf(mAccountForEdit.amount));
			String[] dateParams = mAccountForEdit.date.split("-");
			mYear = Integer.parseInt(dateParams[0]);
	        mMonth = Integer.parseInt(dateParams[1]) - 1;
	        mDay = Integer.parseInt(dateParams[2]);
	        
	        updateDisplay();
		}
    }
    
	@Override
	protected void onResume() {
		mAmountKeybroadView.post(new Runnable() {
			
			@Override
			public void run() {
				mPopupWindow.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT|Gravity.BOTTOM, 0, 0);  
				
			}
		});
		super.onResume();
	}

	@Override
	protected void onPause() {
		mPopupWindow.dismiss();
		super.onPause();
	}

	private void updateDisplay() {
		mAccountDate.setText(CalendarUtils.format(mYear, mMonth, mDay));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.account_date:
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.save_account:
			Account account = new Account();
			account.amount = Double.parseDouble(mAmount.getText().toString());
			account.date = mAccountDate.getText().toString();
			account.firstType = mFirstTypeAdapter.getSelectedItemId();
			account.secondType = mSecondTypeAdapter.getSelectedItemId();
			Request request = new Request(REQ_ACCOUNT_ADD, null);
			request.put(PARAM_ACCOUNT, account);
			AccountLogic.getInstance().sendRequest(request);
			mAmount.getText().clear();
			break;
		case R.id.update_first_type:
			showDialog(DIALOG_UPDATE_FIRST_TYPE);
			break;
		case R.id.update_second_type:
			showDialog(DIALOG_UPDATE_SECOND_TYPE);
			break;
		default:
			break;
		}
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
		final Dialog dialog;
		LinearLayout view;
		Button ok;
		Button cancl;
		LinearLayout dialogContent;
        switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,  mDateSetListener, mYear, mMonth, mDay);
            case DIALOG_UPDATE_FIRST_TYPE:
            case DIALOG_UPDATE_SECOND_TYPE:
            	dialog = new Dialog(this);
    			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    			view = (LinearLayout) View.inflate(this, R.layout.dialog, null);
    			cancl = (Button) view.findViewById(R.id.button_cancl);
    			cancl.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						
					}
				});
    			dialogContent = (LinearLayout) View.inflate(this, R.layout.edit_type_dialog, null);
    			final EditText typeName = (EditText) dialogContent.findViewById(R.id.type_name);
    			final EditText secondTypeName = (EditText) dialogContent.findViewById(R.id.second_type_name);
    			Type temp = null;
    			if (id == DIALOG_UPDATE_SECOND_TYPE) {
    				temp = mSecondTypeAdapter.getSelectedItem();
    			} else {
    				temp = mFirstTypeAdapter.getSelectedItem();
    			}
    			final Type type = temp;
    			typeName.setText(type.name);
    			typeName.setSelection(type.name.length());
    			if (id == DIALOG_UPDATE_SECOND_TYPE) {
					secondTypeName.setVisibility(View.GONE);
				}
    			ok = (Button) view.findViewById(R.id.button_ok);
    			ok.setOnClickListener(new OnClickListener() {
    				
    				@Override
    				public void onClick(View v) {
    					type.name = typeName.getText().toString();
    					Request request = new Request(AccountLogic.REQ_UPDATE_TYPE, EditActivity.this);
    					request.put(AccountLogic.PARAM_TYPE, type);
    					request.putString(AccountLogic.PARAM_TYPE_NAME, secondTypeName.getText().toString());
    					AccountLogic.getInstance().sendRequest(request);
    					dialog.dismiss();
    				}
    			});
    			view.addView(dialogContent, 0);
    			dialog.setContentView(view);
    			return dialog;
            case DIALOG_ADD_TYPE:
            	dialog = new Dialog(this);
            	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    			view = (LinearLayout) View.inflate(this, R.layout.dialog, null);
    			dialogContent = (LinearLayout) View.inflate(this, R.layout.add_type_dialog, null);
    			final EditText firstTypeName = (EditText) dialogContent.findViewById(R.id.type_name);
    			ok = (Button) view.findViewById(R.id.button_ok);
    			ok.setOnClickListener(new OnClickListener() {
    				
    				@Override
    				public void onClick(View v) {
    					Request request = new Request(AccountLogic.REQ_ADD_TYPE, EditActivity.this);
    					request.putString(AccountLogic.PARAM_TYPE_NAME, firstTypeName.getText().toString());
    					AccountLogic.getInstance().sendRequest(request);
    					dialog.dismiss();
    				}
    			});
    			cancl = (Button) view.findViewById(R.id.button_cancl);
    			cancl.setOnClickListener(new OnClickListener() {
    				
    				@Override
    				public void onClick(View v) {
    					dialog.dismiss();
    					
    				}
    			});
    			view.addView(dialogContent, 0);
    			dialog.setContentView(view);
    			return dialog;
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
                break;
        }
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.first_level_type_list:
			mFirstTypeAdapter.setSelectedPosition(position);
			mSecondTypeAdapter.setSelectedPosition(TypeAdapter.NOT_SELECTED_POSITION);
			mSecondTypeAdapter.setData(AccountLogic.getInstance().getType(id).childType);
			break;
		case R.id.second_level_type_list:
			mSecondTypeAdapter.setSelectedPosition(position);
			break;
		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.addSubMenu(0, 0, 0, "增加类型");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			showDialog(DIALOG_ADD_TYPE);
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onRequestFinished(Request request) {
		switch (request.type) {
		case REQ_TYPE_INIT:
			mFirstTypeAdapter.setData(AccountLogic.getInstance().getFirstTypes());
			mFirstTypeAdapter.setSelectedPosition(0);
			mSecondTypeAdapter.setData(AccountLogic.getInstance().getType(mFirstTypeAdapter.getSelectedItemId()).childType);
			if (mAccountForEdit != null) {
				mFirstTypeAdapter.setSelectedItem(mAccountForEdit.firstType);
				mSecondTypeAdapter.setData(AccountLogic.getInstance().getType(mFirstTypeAdapter.getSelectedItemId()).childType);
				mSecondTypeAdapter.setSelectedItem(mAccountForEdit.secondType);
			}
			break;
		case REQ_ADD_TYPE:
			mFirstTypeAdapter.addData((Type) request.getResponseObject(PARAM_TYPE));
			break;
		case REQ_UPDATE_TYPE:
			Type type = (Type) request.getResponseObject(PARAM_TYPE);
			Type secondType = (Type) request.getResponseObject(PARAM_SECOND_TYPE);
			if (type.pID == Type.NO_PID) {
				mFirstTypeAdapter.updateType(type);
			} else {
				mSecondTypeAdapter.updateType(type);
			}
			if (secondType != null) {
				mSecondTypeAdapter.addData(secondType);
			}
			break;
		default:
			break;
		}
	}
	
}